

#include <stdio.h>
#include <stdlib.h>

struct ListNode{
    int val;
    struct ListNode *next;
};

typedef struct ListNode Node, *pNode;

void print(struct ListNode* p)
{
	struct ListNode* q;
	for(q = p; q != NULL; q = q->next)
		printf("[%d]", q->val);
	printf("\n");
}

void setList(struct ListNode * p, int val)
{
	struct ListNode *q;
	q = p;
	while(q->next != NULL)
		q = q->next;
	
	struct ListNode *tmp = (struct ListNode *)malloc(sizeof(struct ListNode));
	if(tmp == NULL)
		return;
	tmp->val = val;
	tmp->next = q->next;
	q->next = tmp;
}

struct ListNode* reverseKGroup(struct ListNode* head, int k) {
	struct ListNode* pCur, *pPre, *pHead;
	struct ListNode* pBreakpoint;
	int i;
	if(head == NULL || head->next == NULL || k < 1)
		return head;
	pCur = head;
	pPre = head;
	pHead = head;
	pBreakpoint = NULL;
	
	for(i = 0; i < k-1; i++)
	{
		pPre = pCur;
		if(pCur->next == NULL)
			return head;
		pCur = pCur->next;
	}
	pBreakpoint = pCur;
	pPre = pCur;
	pCur = head;
	pBreakpoint->next = reverseKGroup(pBreakpoint->next, k);
	while(pCur != pPre)
	{
		pHead = pCur->next;
		pCur->next = pPre->next;
		pPre->next = pCur;
		pCur = pHead;
	}
	head = pHead;

	return head;
}

int main(void)
{
	struct ListNode* head;
	int num[] = {1,2,3,4,5};
	int val = 5;
	int i;
	head = (struct ListNode *)malloc(sizeof(struct ListNode));
	head->val = num[0];
	head->next = NULL;

	for(i = 1; i < sizeof(num)/sizeof(int); i++)
		setList(head, num[i]);
	print(head);
	print(reverseKGroup(head, val));
	return 0;
}